import logging
from os import makedirs
from os.path import join, exists, dirname

from main.config import path
from utils.download_tools import download_img


def save_img(img, name):
    file = join(path, name)
    file_dirname = dirname(file)
    if not exists(file_dirname):
        makedirs(file_dirname)
    try:
        with open(file, 'wb') as f:
            f.write(img)
    except Exception as e:
        logging.info(e)


def download_save_img(img_url, name):
    img = download_img(img_url)

    file = join(path, name)
    file_dirname = dirname(file)
    if not exists(file_dirname):
        makedirs(file_dirname)
    try:
        with open(file, 'wb') as f:
            f.write(img)
    except Exception as e:
        logging.info(e)


def save_jpgs(imgs, folder):
    for i in range(len(imgs)):
        save_img(imgs[i], '{}/{}.jpg'.format(folder, i))


def download_save_jpgs(img_urls, folder):
    if not exists(join(path, folder)):
        makedirs(join(path, folder))
        logging.info('创建文件夹 {}'.format(join(path, folder)))
    for i in range(len(img_urls)):
        download_save_img(img_urls[i], '{}/{}.jpg'.format(folder, i))
